package com.jiusit.onePurchase.interceptor;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jiusit.common.utils.StringUtil;
import com.jiusit.onePurchase.model.ChampionUser;

/**
 * BlogInterceptor 此拦截器仅做为示例展示，在本 demo 中并不需要
 */
public class UserInterceptor implements Interceptor {
	private static final Logger log = Logger.getLogger(UserInterceptor.class);

	public void intercept(Invocation ai) {
		ApiConfig apiConfig = new ApiConfig();

		// 配置微博 API 相关常量
		apiConfig.setToken(PropKit.get("token"));
		apiConfig.setAppId(PropKit.get("appId"));
		apiConfig.setAppSecret(PropKit.get("appSecret"));
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		apiConfig
				.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		apiConfig.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		// 获取微博用户信息
		ApiConfigKit.setThreadLocalApiConfig(apiConfig);
		Controller controller = ai.getController();
		ai.invoke();
		String path = controller.getRequest().getRequestURI();
		log.debug("UserInterceptor  path:" + path);
		String fromUser1 = controller.getCookie("from_User1");
		String access_token = controller.getCookie("accessToken");
		if (fromUser1 == null || fromUser1.equals("") ) {
			fromUser1 = controller.getAttrForStr("from_User1");
			if (fromUser1 == null || fromUser1.equals("")) {
				try {
					// 获取fromUser1
					String code = controller.getPara("code");
					String pass = controller.getPara("pass");
					path = controller.getRequest().getRequestURI();
					if (code == null || "".equals(code)) {
						String redirect_uri1_0 = URLEncoder.encode(
								PropKit.get("host_uri",
										"setting it in config file") + path,
								"utf-8");
						String m1_0 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
								+ PropKit.get("appId")
								+ "&redirect_uri="
								+ redirect_uri1_0
								+ "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
						controller.redirect(m1_0);
						return;
					}
					String userAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
							+ PropKit.get("appId")
							+ "&secret="
							+ PropKit.get("appSecret")
							+ "&code="
							+ code
							+ "&grant_type=authorization_code";
					String userAccessTokenData = HttpKit
							.get(userAccessTokenUrl);
					log.debug("userAccessTokenData:" + userAccessTokenData);
					// 注意userAccessToken一天1000次与2小时限制
					ObjectMapper mapper = new ObjectMapper();
					Map data = mapper.readValue(userAccessTokenData, Map.class);
					if (data.get("openid") != null) {
						String openId=data.get("openid").toString();
						ChampionUser user = ChampionUser.dao.findFirst(
								"select * from champion_user where wb_id=?",
								openId);
						if (user == null) {
							String user_id = StringUtil.getUUID();
							long count=1;
							ChampionUser coutUser=ChampionUser.dao.findFirst("SELECT COUNT(*) AS 'total_num' FROM `champion_user` where user_type='02' ");
							if(coutUser != null ){
								count=coutUser.getLong("total_num");
							}
							if(count == 0){
								count=1;
							}
							String user_name="微信用户"+count;
							ChampionUser championUser = new ChampionUser()
									.set("id", user_id)
									.set("user_name", user_name)
									.set("wb_id", openId)
									.set("head_pic", "")
									.set("energy_currency", 100)
									.set("step_number", 0)
									.set("total_step_number", 0)
									.set("cool_run_number", 0)
									.set("one_cool_run", 0)
									.set("sign_num", 0)
									.set("user_type", "02")
									.set("shake_number", 0)
									.set("create_by", user_id)
									.set("create_name", user_name)
									.set("create_date", new Date())
									.set("update_by", user_id)
									.set("update_name", user_name)
									.set("update_date", new Date());
							championUser.save();

						}
						fromUser1 = openId;
						Cookie cookie = new Cookie("from_User1", fromUser1);
						cookie.setMaxAge(24 * 60 * 60 * 60);
						cookie.setPath("/");
						controller.setCookie(cookie);
					} else {
						log.debug("get openId fail ");
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			  }
			}else{
				Cookie cookie = new Cookie("from_User1", fromUser1);
				cookie.setMaxAge(24 * 60 * 60 * 60);
				cookie.setPath("/");
				controller.setCookie(cookie);
			}
		System.out.println(path);
	}
	
}
